package com.gin.kotlin.no_gay_alliance.argument

import android.os.Parcelable
import android.util.Log
import androidx.sqlite.db.SimpleSQLiteQuery
import androidx.sqlite.db.SupportSQLiteQuery
import kotlinx.parcelize.Parcelize
import java.util.Locale

@Parcelize
data class ReplyHistoryArgument(
    val page: Int = 1,
    val size: Int = 20,
    val topicId: Long? = null,
    val start: Long? = null,
    val end: Long? = null,
    val hasImage: Boolean? = null,
    val anonymous: Boolean? = null,
    val authorUid: Long? = null,
    val keyword: String? = null,
    val username: String? = null,
) : Parcelable {

    /**
     * 根据参数生成 where 子句内容，替换到模板中
     * @param template 查询语句模板， where子句内容使用 %s 占位
     * @return SupportSQLiteQuery
     */
    fun buildSql(template: String): SupportSQLiteQuery {
        // 查询条件
        val conditions = mutableListOf("1=1")
        // 实参
        val args = mutableListOf<Any>()

        topicId?.takeIf { it > 0 }?.also {
            conditions.add("topicId=:topicId")
            args.add(it)
        }

        start?.takeIf { it > 0 }?.also {
            conditions.add("postDateTime>=:start")
            args.add(it)
        }

        end?.takeIf { it > 0 }?.also {
            conditions.add("postDateTime<=:end")
            args.add(it)
        }

        hasImage?.also {
            conditions.add("hasImage=:hasImage")
            args.add(if (it) 1 else 0)
        }

        anonymous?.also {
            conditions.add("anonymous=:anonymous")
            args.add(if (it) 1 else 0)
        }

        authorUid?.takeIf { it > 0 }?.also {
            conditions.add("authorUid=:authorUid")
            args.add(it)
        }

        keyword?.takeIf { it.trim().isNotEmpty() }?.also {k->
            val kws = k.trim().split(" ").filter { it.isNotEmpty() }
            conditions.add(kws.withIndex().joinToString(" and ","(",")") {
                "content like '%' || :k${it.index} || '%'"
            })
            args.addAll(kws)
        }

        username?.takeIf { it.trim().isNotEmpty() }?.also{
            conditions.add("username like '%' || :username || '%'")
            args.add(it.trim())
        }

        val where = conditions.joinToString(" and ")
        val sql = String.format(Locale.CHINESE, template, where)
        Log.i(TAG, "sql: $sql")
        Log.i(TAG, "args: $args")
        return SimpleSQLiteQuery(sql, args.toTypedArray())
    }

    companion object{
        private val TAG = ReplyHistoryArgument::class.java.simpleName
    }

}
